# -*- coding: utf-8 -*-
# brand_wordcloud_match.py
# Created by Hardy on 17th, Feb
# Copyright 2017 杭州网川教育有限公司. All rights reserved.

from querier.esquerier import ElasticSearchQuerier


WORDCLOUD_TOP_N = 100
MINIMUM_SHOULD_MATCH = "5<85% 10<9"


class BrandWordCloudMatchResource(ElasticSearchQuerier):
    def __init__(self, es, index, doc_type):
        super(BrandWordCloudMatchResource, self).__init__(None, None, None)
        self.es = es
        self.index = index
        self.doc_type = doc_type

    def _build_query(self, args):
        biz_code = args.get('biz_code', None)
        biz_name = args.get('biz_name', None)
        class1_id = args.get('class1_id', None)
        class1_name = args.get('class1_name', None)
        query_keywords = args.get('term', None)
        from_ = args.get('from', 0)
        from_ = from_ if from_ else 0
        size_ = args.get('size', 10)
        size_ = size_ if size_ else 10

        query = self._gen_query(biz_code, biz_name, class1_id, class1_name, query_keywords, from_, size_)
        return query, {}, {'biz_code': biz_code, 'biz_name': biz_name, 'class1_id': class1_id,
                           'class1_name': class1_name, 'query_keywords': query_keywords}

    def _build_result(self, es_result, param):
        # biz_code = param['biz_code']
        # biz_name = param['biz_name']
        # class1_id = param['class1_id']
        # class1_name = param['class1_name']
        query_keywords = param['query_keywords'].split(' ')
        total = es_result['hits']['total']
        brands = []
        for hit in es_result['hits']['hits']:
            brands.append(extract_result(hit, query_keywords))
        return {
            'total': total,
            'brands': brands

        }

    @staticmethod
    def _gen_query(biz_code, biz_name, class1_id, class1_name, query_keywords, from_, size_):
        should_clause = []
        if biz_code:
            should_clause.append(
                {
                    "match": {
                        "biz_code":
                            {"query": biz_code,
                             "minimum_should_match": MINIMUM_SHOULD_MATCH
                             }
                    }
                }
            )
        if biz_name:
            should_clause.append(
                {
                    "match": {
                        "biz_name":
                            {"query": biz_name,
                             "minimum_should_match": MINIMUM_SHOULD_MATCH
                             }
                    }
                }
            )
        if class1_id:
            should_clause.append(
                {
                    "match": {
                        "class1_id":
                            {"query": class1_id,
                             "minimum_should_match": MINIMUM_SHOULD_MATCH
                             }
                    }
                }
            )
        if class1_name:
            should_clause.append(
                {
                    "match": {
                        "class1_name":
                            {"query": class1_name,
                             "minimum_should_match": MINIMUM_SHOULD_MATCH
                             }
                    }
                }
            )
        if query_keywords:
            should_clause.append(
                {
                    'multi_match': {
                            "analyzer": "whitespace",
                            'query': query_keywords,
                            'fields': ['class1_name_seg', 'brand^4', 'keywords'],
                            # 'minimum_should_match': utils.MINIMUM_SHOULD_MATCH

                    }
                }
            )
        query = {
            "from": from_,
            "size": size_,
            "query": {
                "bool": {
                    "should": should_clause
                }
            }
        }

        return query


def extract_result(hit, query_keywords=()):
    source_ = hit['_source']
    kv = dict(zip(source_['keywords'], source_['weight']))
    freq = sum([kv.get(k, 0) for k in query_keywords])
    if source_['brand'] in query_keywords:
        freq += 100
    # score_ = hit['_score']
    return {
        'score': hit['_score'] * freq,
        'brand': source_['brand'],
        'biz_code': source_['biz_code'],
        'biz_name': source_['biz_name'],
        'class1_id': source_['class1_id'],
        'class1_name': source_['class1_name'],
        'keywords': source_['keywords'][0:WORDCLOUD_TOP_N],
        'weight': source_['weight'][0:WORDCLOUD_TOP_N],
        'keywords_weight': kv
    }
